﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xaml;
using System.CodeDom;
using System.Diagnostics;
using System.Windows.Markup;
using System.ComponentModel.Composition;

namespace NeuroSpeech.XamlExtensions
{
    [Export]
    public class ReferenceConverter : GenericConverter<Reference>
    {


        #region public override System.CodeDom.CodeStatement  Assign(XamlCodeContext context, System.CodeDom.CodeExpression target, System.CodeDom.CodeExpression value)
        public override CodeStatement Assign(XamlCodeContext context, CodeExpression target, CodeExpression value)
        {

            CodeVariableDeclarationStatement vs = context.GetLastStatement<CodeVariableDeclarationStatement>(context.PreStatements);
            CodeObjectCreateExpression cc = vs.InitExpression as CodeObjectCreateExpression;
            CodePrimitiveExpression pr = cc.Parameters[0] as CodePrimitiveExpression;
            context.PreStatements.Remove(vs);
            string name = pr.Value as string;


            CodeAssignStatement cas = new CodeAssignStatement { 
                Left = target,
                Right = new CodeFieldReferenceExpression{ 
                    TargetObject = new CodeThisReferenceExpression(),
                    FieldName = name
                }
            };

            context.Statements.Add(cas);

            return null;
        }
        #endregion



    }
}
